package org.jks.service.impl;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.jks.model.Category;
import org.springframework.stereotype.Repository;

@Repository("CategoryServiceImpl")
public class CategoryServiceImpl extends BaseDaoImpl<Category>{
	public void save(List<Category> categories){
		Session session = this.openSession();
		session.beginTransaction();
		for(Category category : categories){
			session.save(category);
		}
		session.getTransaction().commit();
		session.flush();
		session.close();
	}
	
	public void update(List<Category> categories){
		Session session = this.openSession();
		for(Category category : categories){
			session.update(category);
		}
		session.flush();
		session.close();
	}
	
	public List<Category> all() {
		return find("from Category");
	}
	
	public List<Category> listpage(int page, int pagesize){
		List<Object> param = null;
		return find("from Category", param, page, pagesize);
	}
	
	public long count(){
		return count("select count(*) from Category");
	}
	
	public Category findById(long id){
		return get(Category.class, id);
	}

	public void delete(long id) {
		Session session = this.openSession();
		session.delete(session.load(Category.class, id));
		session.flush();
		session.close();
	}

	public void delete(Object[] ids) {
		Session session = this.openSession();
		StringBuilder strIds = new StringBuilder();
		strIds.append('(');
		int imax = ids.length-1;
        for (int i = 0; ; i++) {
        	strIds.append(ids[i]);
        	if(i == imax){
        		strIds.append(')');
        		break;
        	}
        	strIds.append(", ");
        }
		SQLQuery sqlQuery = session.createSQLQuery("delete from category where id in " + strIds);
		sqlQuery.executeUpdate();
		session.flush();
		session.close();
	}
}
